<template>
  <div class="cluster-monitor">
    <div class="monitor-header">
      <h2>🖥️ 集群监控面板</h2>
      <button @click="refreshHealth" class="refresh-btn" :disabled="loading">
        {{ loading ? '检查中...' : '🔄 刷新' }}
      </button>
    </div>

    <div class="cluster-status">
      <div class="status-overview">
        <div class="overview-item">
          <span class="label">集群状态:</span>
          <span class="value" :class="overallStatus">{{ overallStatusText }}</span>
        </div>
        <div class="overview-item">
          <span class="label">活跃节点:</span>
          <span class="value">{{ activeNodes }}/{{ clusterNodes.length }}</span>
        </div>
        <div class="overview-item">
          <span class="label">当前服务器:</span>
          <span class="value">{{ currentServer }}</span>
        </div>
      </div>

      <div class="nodes-grid">
        <div v-for="node in clusterNodes" :key="node.url" class="node-card" :class="node.status">
          <div class="node-header">
            <h3>{{ node.instanceId || '未知节点' }}</h3>
            <span class="status-badge" :class="node.status">
              {{ node.status === 'UP' ? '✅ 正常' : '❌ 异常' }}
            </span>
          </div>

          <div class="node-info">
            <div class="info-item">
              <span class="label">地址:</span>
              <span class="value">{{ node.url }}</span>
            </div>
            <div class="info-item">
              <span class="label">端口:</span>
              <span class="value">{{ node.port }}</span>
            </div>
            <div class="info-item">
              <span class="label">Redis:</span>
              <span class="value" :class="node.redisStatus === 'CONNECTED' ? 'connected' : 'disconnected'">
                {{ node.redisStatus || '未知' }}
              </span>
            </div>
            <div class="info-item">
              <span class="label">最后检查:</span>
              <span class="value">{{ node.timestamp }}</span>
            </div>
          </div>

          <div class="node-actions">
            <button
              @click="switchToNode(node.url)"
              class="switch-btn"
              :disabled="currentServer === node.url"
            >
              {{ currentServer === node.url ? '当前' : '切换' }}
            </button>
          </div>
        </div>
      </div>
    </div>

    <div class="session-test">
      <h3>🔐 会话共享测试</h3>
      <div class="test-panel">
        <button @click="testSession" class="test-btn" :disabled="testingSession">
          {{ testingSession ? '测试中...' : '测试会话' }}
        </button>

        <div v-if="sessionData" class="session-result">
          <h4>会话信息:</h4>
          <div class="session-info">
            <p><strong>会话ID:</strong> {{ sessionData.sessionId }}</p>
            <p><strong>访问次数:</strong> {{ sessionData.visitCount }}</p>
            <p><strong>服务节点:</strong> {{ sessionData.instanceId }}</p>
            <p><strong>最后访问:</strong> {{ sessionData.lastAccess }}</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { childEnglishApi } from '@/api/childEnglishApi';

export default {
  name: 'ClusterMonitor',
  data() {
    return {
      loading: false,
      testingSession: false,
      clusterNodes: [],
      sessionData: null,
      currentServer: childEnglishApi.getCurrentServer()
    };
  },
  computed: {
    overallStatus() {
      const upNodes = this.clusterNodes.filter(node => node.status === 'UP').length;
      if (upNodes === this.clusterNodes.length) return 'healthy';
      if (upNodes > 0) return 'degraded';
      return 'unhealthy';
    },
    overallStatusText() {
      const upNodes = this.clusterNodes.filter(node => node.status === 'UP').length;
      return `${upNodes}/${this.clusterNodes.length} 节点正常`;
    },
    activeNodes() {
      return this.clusterNodes.filter(node => node.status === 'UP').length;
    }
  },
  async mounted() {
    await this.refreshHealth();
  },
  methods: {
    async refreshHealth() {
      this.loading = true;
      try {
        const healthStatus = await childEnglishApi.checkClusterHealth();
        this.clusterNodes = healthStatus.map(item => ({
          url: item.url,
          status: item.status,
          instanceId: item.data?.data?.instanceId || '未知',
          port: item.data?.data?.port || '未知',
          redisStatus: item.data?.data?.redis || '未知',
          timestamp: new Date().toLocaleTimeString()
        }));
      } catch (error) {
        console.error('获取集群状态失败:', error);
      } finally {
        this.loading = false;
      }
    },

    switchToNode(url) {
      const index = ['http://localhost:8080', 'http://localhost:8081', 'http://localhost:8082'].indexOf(url);
      if (index !== -1) {
        childEnglishApi.switchServer(index);
        this.currentServer = childEnglishApi.getCurrentServer();
        alert(`已切换到节点: ${url}`);
      }
    },

    async testSession() {
      this.testingSession = true;
      try {
        const response = await childEnglishApi.sessionTest();
        if (response.code === 200) {
          this.sessionData = response.data;
          alert('会话测试成功！');
        }
      } catch (error) {
        console.error('会话测试失败:', error);
        alert('会话测试失败');
      } finally {
        this.testingSession = false;
      }
    }
  }
};
</script>

<style scoped>
.cluster-monitor {
  padding: 20px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.monitor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.refresh-btn {
  padding: 8px 16px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
}

.refresh-btn:disabled {
  background: #bdc3c7;
  cursor: not-allowed;
}

.status-overview {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.overview-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.overview-item .label {
  font-weight: bold;
  color: #2c3e50;
}

.overview-item .value {
  font-weight: bold;
}

.overview-item .value.healthy {
  color: #27ae60;
}

.overview-item .value.degraded {
  color: #f39c12;
}

.overview-item .value.unhealthy {
  color: #e74c3c;
}

.nodes-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.node-card {
  padding: 20px;
  border-radius: 8px;
  border: 2px solid #e0e0e0;
  transition: all 0.3s ease;
}

.node-card.UP {
  border-color: #27ae60;
  background: #f8fff8;
}

.node-card.DOWN {
  border-color: #e74c3c;
  background: #fff8f8;
  opacity: 0.6;
}

.node-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.node-header h3 {
  margin: 0;
  color: #2c3e50;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: bold;
}

.status-badge.UP {
  background: #d4edda;
  color: #155724;
}

.status-badge.DOWN {
  background: #f8d7da;
  color: #721c24;
}

.node-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 15px;
}

.info-item {
  display: flex;
  justify-content: space-between;
}

.info-item .label {
  color: #7f8c8d;
}

.info-item .value {
  color: #2c3e50;
  font-weight: 500;
}

.info-item .value.connected {
  color: #27ae60;
}

.info-item .value.disconnected {
  color: #e74c3c;
}

.node-actions {
  text-align: center;
}

.switch-btn {
  padding: 6px 12px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.switch-btn:disabled {
  background: #bdc3c7;
  cursor: not-allowed;
}

.session-test {
  border-top: 1px solid #eee;
  padding-top: 20px;
}

.session-test h3 {
  margin-bottom: 15px;
  color: #2c3e50;
}

.test-panel {
  text-align: center;
}

.test-btn {
  padding: 10px 20px;
  background: #9b59b6;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  margin-bottom: 15px;
}

.test-btn:disabled {
  background: #bdc3c7;
  cursor: not-allowed;
}

.session-result {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 6px;
  text-align: left;
}

.session-result h4 {
  margin: 0 0 10px 0;
  color: #2c3e50;
}

.session-info p {
  margin: 5px 0;
  color: #5d6d7e;
}
</style>
